package db

import (
	"errors"
	myorm "filestore-rebuild/db/orm"
	"filestore-rebuild/models"
	"log"
)

func InsertFile(file models.File) error {
	var tmpFile models.File
	db := myorm.GetDB()
	db.Where("file_sha1 = ?", file.FileSha1).First(&tmpFile)
	if tmpFile.FileSha1 == file.FileSha1 {
		log.Println("file exists")
		return nil
	}
	db.Create(&file)
	return nil
}

func ListFile() []models.File {
	// TODO 分页
	var files []models.File
	db := myorm.GetDB()
	db.Find(&files)
	return files
}

func SelectFileBySha1AndFileSize(fileSha1 string, fileSize int64) (models.File, error) {
	var file models.File
	db := myorm.GetDB()
	db.Where("file_sha1 = ? and file_size = ?", fileSha1, fileSize).First(&file)
	if file.ID == 0 {
		return file, errors.New("file not found")
	}
	return file, nil
}
